/**
 * @name App
 * @description
 * @author darcrand
 */

import React from "react";
import axios from "axios";
import NodeRSA from "node-rsa-build";
import "./App.css";

const rsa = new NodeRSA({ b: 512 });

const App = () => {
  const [tab, setTab] = React.useState("1");
  const ref = React.useRef();
  const [info, setInfo] = React.useState({});

  const onSubmit = async (e) => {
    e && e.preventDefault();
    const data = new FormData(ref.current);

    const form = {};
    for (const v of data.entries()) {
      form[v[0]] = v[1];
    }

    // 配置公钥
    const keyRes = await axios.get("/api/auth/get-key");
    const publicKey = keyRes.data;
    rsa.importKey(publicKey, "pkcs8-public");

    // 注册
    if (tab === "1") {
      await axios.post("/api/user/signup", {
        username: form.username,
        password: rsa.encrypt(form.password, "base64"),
        role: form.role,
      });
    } else {
      // 登录
      const res = await axios.post("/api/user/login", {
        username_field: form.username,
        password_field: rsa.encrypt(form.password, "base64"),
      });

      window.localStorage.setItem("token", res.data.access_token);
      setInfo(res.data.user);
    }
  };

  return (
    <>
      <section>
        <i className={tab === "1" ? "active" : ""} onClick={() => setTab("1")}>
          注册
        </i>
        <i className={tab === "2" ? "active" : ""} onClick={() => setTab("2")}>
          登录
        </i>
      </section>

      <form ref={ref} onSubmit={onSubmit}>
        <input type="text" name="username" />
        <input type="text" name="password" />

        <section style={{ display: tab === "1" ? "block" : "none" }}>
          <label>
            <input type="radio" name="role" value="account" defaultChecked />
            <span>普通用户</span>
          </label>
          <label>
            <input type="radio" name="role" value="admin" />
            <span>管理员</span>
          </label>
        </section>

        <p>
          <button type="submit">{tab === "1" ? "注册账号" : "立即登录"}</button>
        </p>
      </form>

      <p>
        <span>user: </span>
        <code>{JSON.stringify(info)}</code>
      </p>

      <p>
        <button
          onClick={() => {
            axios.get("/api/user/get-info", {
              headers: {
                Authorization: `Bearer ${window.localStorage.getItem("token")}`,
              },
            });
          }}
        >
          获取当前用户信息(需要token)
        </button>

        <button
          onClick={() => {
            axios.get("/api/user/list");
          }}
        >
          获取所有用户列表（不需要token）
        </button>

        <button
          onClick={() => {
            axios.get("/api/user/get-admin-data", {
              headers: {
                Authorization: `Bearer ${window.localStorage.getItem("token")}`,
              },
            });
          }}
        >
          获取管理员信息（需要token，并且是管理员角色）
        </button>
      </p>

      <blockquote>打开控制台查看接口请求</blockquote>
    </>
  );
};

export default App;
